SUIPatternLibrary.PopupController = (function($, _, app){
var
    port,

    init = function(){
        initEvents();
        initViews();
        initConnection();
    },

    initViews = function(){
        app.TabView.init(app.Model);
    },

    initConnection = function(){
        chrome.tabs.getSelected(null, function(tab) {
            port = chrome.tabs.connect(tab.id);
            port.onMessage.addListener(function(json){
                var event = JSON.parse(json);
                onContentScriptMessage(event.type, event.data);
            });
        });
    },

    onContentScriptMessage = function(event, data){
        console.log(event, data);
    },

    initEvents = function(){
        app.TabView.on("engineSelected", function(event, engineName){
            port.postMessage({
                type : "engineSelected",
                data : engineName
            });
        });
        app.TabView.on("patternHover", function(event, patternName){
            port.postMessage({
                type : "patternHover",
                data : patternName
            });
            highlightPattern(patternName);
        });
        app.TabView.on("patternClick", function(event, patternName){
            port.postMessage({
                type : "patternClick",
                data : patternName
            });
        });
		app.TabView.on("activate", function(event, active){
			port.postMessage({
				type : "activate",
				data : active
			});
		});
    },

    displayPatternSelectDialog = function(patternNames){
        var dialog = app.PatternSelectDialog();
        dialog.init(patternNames);
        $(dialog).on("patternClick", function(event, patternName){
            displayPatternDetails(patternName);
        });
    },

    displayPatternDetails = function(patternName){
        var pattern = app.Model.getPatternByName(patternName);
        if(pattern == undefined) return;
        var detailView = app.PatternDetailView();
        detailView.init(pattern);
        detailView.on("patternClick", function(event, patternName){
            displayPatternDetails(patternName);
        });
    },

    highlightPattern = function(patternName){
        if(patternName == undefined){
            app.TabView.unhighlitghtAll();
        }
        app.TabView.highlightPattern(patternName);
    };

    return {
        init: init
    };

}(jQuery, _, SUIPatternLibrary));